/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cardarus.operatingsystem.struts.actions;

import com.cardarus.operatingsystem.struts.forms.RegisterRewardInputForm;
import com.cardarus.operatingsystem.model.BusinessModel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.cardarus.operatingsystem.domain.Customer;
import javax.servlet.http.HttpSession;

/**
 * This class responds to confirming Customer's registration of Reward plan.
 * This class will display concerning information to Customer and
 * let them confirm those information.
 * @author Daqi
 */
public class RegisterRewardConfirmAction extends org.apache.struts.action.Action {

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        RegisterRewardInputForm formBean = (RegisterRewardInputForm) form;
        BusinessModel model = BusinessModel.getInstance();

        HttpSession session = request.getSession();

        boolean newUser = formBean.isNewUser();
        Customer user = null;

        String pin;

        if (newUser) {
            user = new Customer();
            user.setAddress(formBean.getAddress());
            user.setEmail(formBean.getEmail());
            user.setFamilyName(formBean.getFamilyName());
            user.setName(formBean.getName());
            user.setBirthday(formBean.getBirthday());
            user.setPassword(formBean.getPassword());
            user.setPhone(formBean.getPhone());
            user.setUserName(formBean.getUserName());

            //Create new Customer
            if (model.createNewCustomer(user)) {
                pin = user.getPin();
                formBean.setPin(pin);
                user = model.getCustomerByPin(pin);
            } else {
                return mapping.findForward("error");
            }
        } else {
            user = (Customer) session.getAttribute("user");
        }

        if (model.registerReward(user)) {
            session.setAttribute("user", user);
            return mapping.findForward("success");
        } else {
            return mapping.findForward("error");
        }
    }
}
